import Vue from 'vue'
import App from './App.vue'
//引入路由
import VueRouter from 'vue-router'
import router from './router/index.js'
Vue.use(VueRouter)
//引入vuex
import store from './store/index';

//引入elementui
import ElementUI from 'element-ui'
Vue.use(ElementUI)
import 'element-ui/lib/theme-chalk/index.css'
//全局引入样式
import '@/assets/css/style.css';
import '@/assets/css/ShopShow.css';
import '@/assets/css/MagicZoom.css';
Vue.config.productionTip = false
//引入axios
import  axios from 'axios'
Vue.prototype.$axios = axios;
//axios请求拦截器
axios.interceptors.request.use(
  config=>{
    //加入token
    let token = window.sessionStorage.getItem("token");
    if(token){
      config.headers['Authorization'] = token;
    }
    return config;
}),
  error=>{
    console.log("前置拦截器错误");
    Promise.reject(error);
}
//axios响应拦截器
axios.interceptors.response.use(
  response=>{
    //判断后端是否携带了token延期的信息
    let xtoken = response.headers['x-token'];
    if(xtoken){
      window.sessionStorage.setItem("token",xtoken);
    }
    return response;
},error=>{
    // console.log("后置拦截器错误",error);
      //处理用户登录的错误
      switch(error.response.data.code){
        case "4000":
          Vue.prototype.$message.error('服务器错误！');
          break;
        case "4001":
          Vue.prototype.$message.error('用户名或密码错误!');
          break;
        case "4002":
          Vue.prototype.$message.error('登录超时，请重新登录！');
          window.sessionStorage.removeItem('token');
          window.sessionStorage.removeItem('userName');
          window.sessionStorage.removeItem('userRole');
          window.sessionStorage.removeItem('collects');
          store.commit('changeLoginStatus',false);
          store.commit('getUserName','');
          store.commit('changeUserRole','');
          store.commit('changeCollects',[]);
          router.push('/login');
          break;
        case "4005":
          Vue.prototype.$message.error('权限不足！');
          break;
        case "4006":
          Vue.prototype.$message.error('请先登录！');
          router.push('/login');
          break;
        case "4007":
          Vue.prototype.$message.error('验签错误,请重新登录！');
          
      }
    return Promise.reject(error);
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
